package org.example.xiaomi.dao.impl;

import org.example.xiaomi.dao.CategoryDao;
import org.example.xiaomi.entity.Category;
import org.example.xiaomi.service.CategoryService;
import org.example.xiaomi.tx.TransactionManager;
import org.example.xiaomi.vo.ResultVO;

import java.util.List;
import java.util.Map;

public class CategoryServiceImpl implements CategoryService {
    private CategoryDao categoryDao=new Sql2oCategoryDaoImpl();
    @Override
    public List<Category> getCategoryList(int page, int limit, Map<String, Object> searchMap) {
        return categoryDao.find(page,limit,searchMap);
    }

    @Override
    public long getCategoryCount(Map<String, Object> searchMap) {
        return categoryDao.getCount(searchMap);
    }

    @Override
    public ResultVO addCategory(Category category) {
        try {
            TransactionManager.beginTransaction();
            Category dbCate = categoryDao.findByName(category.getName());
            if (dbCate != null) {
                return ResultVO.fail("名字已经存在");
            }
            int ret = categoryDao.save(category);
            TransactionManager.commitTransaction();
            if (ret > 0) {
                return ResultVO.success(ret);
            }else {
                return ResultVO.fail("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionManager.rollbackTransaction();
            return  ResultVO.fail(e.getMessage());
        }

    }

    @Override
    public ResultVO updateCategory(Category category) {
        try {
            TransactionManager.beginTransaction();
            Category dbCate = categoryDao.findByName(category.getName());
            if (dbCate != null) {
                return ResultVO.fail("名字已经存在");
            }
            int ret = categoryDao.update(category);
            TransactionManager.commitTransaction();
            if (ret > 0) {
                return ResultVO.success(ret);
            }else {
                return  ResultVO.fail("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionManager.rollbackTransaction();
            return  ResultVO.fail(e.getMessage());
        }
    }

    @Override
    public int deleteCategory(Long categoryId) {
        try {
            TransactionManager.beginTransaction();
            int ret = categoryDao.delete(categoryId);
            TransactionManager.commitTransaction();
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionManager.rollbackTransaction();
            return  0;
        }
    }
}
